﻿
 
using Microsoft.EntityFrameworkCore;
using ST.Core;
using System.Linq.Expressions;
using System.Reflection;


namespace ST.Data
{
    public partial class Repository<TEntity> : IRepository<TEntity> where TEntity : Int64Model
    {
        AppDbContext _DB =null;
        public Repository(AppDbContext db )
        {
            _DB = db;

        }

        public AppDbContext DB
        {
            get {
                  
                return _DB;
            }set{
                _DB = value;
            }
        }
        public IQueryable<TEntity> GetAll(bool includeDeleted = false)
        {
            var query= DB.Set<TEntity>().AsQueryable();
            
            if (typeof(TEntity).GetInterface(nameof(ISoftDeletedEntity)) == null)
                return query;
            if (includeDeleted)
            {
                return query;
            }
            return query.OfType<ISoftDeletedEntity>().Where(entry => !entry.Deleted).OfType<TEntity>();
                        
        }
        public Task<int>  SaveChagnesAsync()
        { 
                return DB.SaveChangesAsync();
        }
       
        public int SaveChagnes()
        {
         
            return DB.SaveChanges();
        }
        public    TEntity  GetById(long id)
        {
            var m =   GetAll().Where(a => a.Id == id).FirstOrDefault();
            return m;
        }
      
        public async Task<TEntity> GetByIdAsync(long id)
        {
            var m = await GetAll().Where(a => a.Id == id).FirstOrDefaultAsync();
            return m;
        }
        public TEntity GetById(Int64Model qm)
        {
            return GetById(qm.Id);
        }


        public   List<TEntity> GetByIds(List<long> lid)
        {
            var l =   GetAll().Where(a => lid.Contains(a.Id)).ToList();
            return l;
        }
        public async Task<List<TEntity>> GetByIdsAsync(List<long> lid)
        {
            var l = await GetAll().Where(a => lid.Contains(a.Id)).ToListAsync();
            return l;
        }

         


    }

}
